package com.icongyou.enterprise.talent_pool.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@Slf4j
@Service
@RequiredArgsConstructor
public class AIModelService {

    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;

    @Value("${ai.api.url}")
    private String aiModelApiUrl;

    @Value("${ai.api.key}")
    private String aiModelApiKey;

    @Value("${ai.model}")
    private String aiModel;


    /**
     * 调用大模型API
     */
    public Map<String, Object> callAIModelAPI(Map<String, Object> request) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + aiModelApiKey);

            // 添加其他必要的请求头
            headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(request, headers);


            Map<String, Object> response = restTemplate.postForObject(aiModelApiUrl, entity, Map.class);

            return response;

        } catch (Exception e) {
            throw new RuntimeException("大模型API调用失败", e);
        }
    }

    /**
     * 构建大模型请求（移除请求头设置）
     */
    public Map<String, Object> buildAIModelRequest(String prompt) {
        Map<String, Object> request = new HashMap<>();
        Map<String, Object> input = new HashMap<>();
        Map<String, Object> parameters = new HashMap<>();

        input.put("messages", List.of(
                Map.of("role", "system", "content", "你是一个教育领域的任务分析专家，请分析文本相关的技术标签并给出关联度分数（0-1）。"),
                Map.of("role", "user", "content", prompt)
        ));

        parameters.put("temperature", 0.3);
        parameters.put("max_tokens", 2000);

        request.put("model", aiModel);
        request.put("input", input);
        request.put("parameters", parameters);

        return request;
    }


    /**
     * 专门用于任务分析的标签提取方法
     */
    public List<TagAnalysisResult> analyzeAssignmentTags(String assignmentDescription) {

        String prompt = buildAssignmentAnalysisPrompt(assignmentDescription);
        Map<String, Object> request = buildAIModelRequest(prompt);

        try {
            Map<String, Object> response = callAIModelAPI(request);
            return parseAssignmentTagResponse(response);
        } catch (Exception e) {
            return getFallbackAssignmentAnalysisResults(assignmentDescription);
        }
    }

    /**
     * 构建任务分析提示词（用于预计算）
     */
    private String buildAssignmentAnalysisPrompt(String assignmentDescription) {
        return String.format(
                "请分析以下任务描述，自动生成3-5个最相关的技术标签并给出关联度分数（0-1，1表示强相关）。\n\n" +
                        "同时，请为每个标签识别近似标签（同义词、缩写等）。例如：\n" +
                        "- \"人工智能\" 的近似标签是 [\"AI\", \"人工智慧\"]\n" +
                        "- \"机器学习\" 的近似标签是 [\"ML\", \"Machine Learning\"]\n" +
                        "- \"数据库\" 的近似标签是 [\"DB\", \"Database\"]\n" +
                        "注意：\"人工智能\" 和 \"机器学习\" 不是近似标签，它们是不同的概念。\n\n" +
                        "任务描述：%s\n\n" +
                        "请返回纯JSON格式，不要包含任何其他文本或Markdown标记：{\"tags\": [{\"tagName\": \"标签名称\", \"relevance\": 0.8, \"similarTags\": [\"近似标签1\", \"近似标签2\"]}, ...]}",
                assignmentDescription
        );
    }

    /**
     * 解析任务分析响应（适配阿里云DashScope）
     */
    @SuppressWarnings("unchecked")
    private List<TagAnalysisResult> parseAssignmentTagResponse(Map<String, Object> response) {
        try {

            // 检查响应中是否包含错误信息
            if (response.containsKey("code")) {
                return Collections.emptyList();
            }

            // 阿里云DashScope返回结构
            Map<String, Object> output = (Map<String, Object>) response.get("output");
            if (output == null) {
                return Collections.emptyList();
            }

            // DashScope返回的内容在output.text中
            String content = (String) output.get("text");
            if (content == null || content.trim().isEmpty()) {
                return Collections.emptyList();
            }

            return parseMultiTagAnalysisResults(content);

        } catch (Exception e) {
            return Collections.emptyList();
        }
    }

    /**
     * 解析多标签分析结果（包含关联度，用于任务分析）
     */
    @SuppressWarnings("unchecked")
    private List<TagAnalysisResult> parseMultiTagAnalysisResults(String content) {
        try {
            // 清理Markdown代码块标记
            String cleanedContent = cleanJsonContent(content);

            Map<String, Object> tagResult = objectMapper.readValue(cleanedContent, Map.class);
            List<Map<String, Object>> tags = (List<Map<String, Object>>) tagResult.get("tags");

            if (tags == null || tags.isEmpty()) {
                return Collections.emptyList();
            }

            List<TagAnalysisResult> results = new ArrayList<>();
            for (Map<String, Object> tag : tags) {
                try {
                    String tagName = (String) tag.get("tagName");
                    Double relevance = ((Number) tag.get("relevance")).doubleValue();
                    List<String> similarTags = (List<String>) tag.get("similarTags");

                    if (tagName != null && !tagName.trim().isEmpty()) {
                        TagAnalysisResult result = new TagAnalysisResult();
                        result.setTagName(tagName.trim());
                        result.setRelevance(relevance);
                        result.setSimilarTags(similarTags != null ? similarTags : Collections.emptyList());
                        results.add(result);
                    }
                } catch (Exception e) {
                }
            }

            return results;

        } catch (Exception e) {
            return Collections.emptyList();
        }
    }

    /**
     * 任务分析的降级方案
     */
    private List<TagAnalysisResult> getFallbackAssignmentAnalysisResults(String text) {

        List<TagAnalysisResult> fallbackResults = new ArrayList<>();

        // 常见的技术标签关键词
        String[] commonTechTags = {"Java", "Python", "JavaScript", "数据库", "算法", "机器学习",
                "前端", "后端", "移动开发", "云计算", "大数据", "人工智能"};

        String lowerText = text.toLowerCase();

        for (String tag : commonTechTags) {
            if (lowerText.contains(tag.toLowerCase())) {
                TagAnalysisResult result = new TagAnalysisResult();
                result.setTagName(tag);
                result.setRelevance(0.7);
                result.setSimilarTags(Collections.emptyList());
                fallbackResults.add(result);

                // 最多返回5个标签
                if (fallbackResults.size() >= 5) {
                    break;
                }
            }
        }

        // 如果没有任何匹配，返回一个默认标签
        if (fallbackResults.isEmpty()) {
            TagAnalysisResult result = new TagAnalysisResult();
            result.setTagName("技术开发");
            result.setRelevance(0.5);
            result.setSimilarTags(Collections.emptyList());
            fallbackResults.add(result);
        }

        return fallbackResults;
    }


    /**
     * 专门用于需求分析的标签提取方法（不包含关联度）
     */
    public List<TagDemandAnalysisResult> analyzeDemandTags(String demandText) {

        String prompt = buildDemandAnalysisPrompt(demandText);
        Map<String, Object> request = buildAIModelRequest(prompt);

        try {
            Map<String, Object> response = callAIModelAPI(request);
            return parseDemandTagResponse(response);
        } catch (Exception e) {
            return getFallbackDemandAnalysisResults(demandText);
        }
    }

    /**
     * 构建需求分析提示词（用于人才需求提取）
     */
    private String buildDemandAnalysisPrompt(String demandText) {
        return String.format(
                "请分析以下人才需求描述，提取1-4个最相关的技术标签。\n\n" +
                        "同时，请为每个标签识别近似标签（同义词、缩写等）。例如：\n" +
                        "- \"人工智能\" 的近似标签是 [\"AI\", \"人工智慧\"]\n" +
                        "- \"机器学习\" 的近似标签是 [\"ML\", \"Machine Learning\"]\n" +
                        "- \"数据库\" 的近似标签是 [\"DB\", \"Database\"]\n" +
                        "注意：\"人工智能\" 和 \"机器学习\" 不是近似标签，它们是不同的概念。\n\n" +
                        "人才需求描述：%s\n\n" +
                        "请返回纯JSON格式，不要包含任何其他文本或Markdown标记：{\"tags\": [{\"tagName\": \"标签名称\", \"similarTags\": [\"近似标签1\", \"近似标签2\"]}, ...]}",
                demandText
        );
    }

    /**
     * 解析需求分析响应（适配阿里云DashScope）
     */
    @SuppressWarnings("unchecked")
    private List<TagDemandAnalysisResult> parseDemandTagResponse(Map<String, Object> response) {
        try {
            Map<String, Object> output = (Map<String, Object>) response.get("output");
            if (output != null) {
                String content = (String) output.get("text");
                if (content != null && !content.trim().isEmpty()) {
                    return parseDemandTagAnalysisResults(content);
                } else {
                }
            } else {
            }
        } catch (Exception e) {
        }
        return Collections.emptyList();
    }

    /**
     * 解析需求标签分析结果（不包含关联度）
     */
    @SuppressWarnings("unchecked")
    private List<TagDemandAnalysisResult> parseDemandTagAnalysisResults(String content) {
        try {
            // 清理Markdown代码块标记
            String cleanedContent = cleanJsonContent(content);

            Map<String, Object> tagResult = objectMapper.readValue(cleanedContent, Map.class);
            List<Map<String, Object>> tags = (List<Map<String, Object>>) tagResult.get("tags");

            if (tags == null || tags.isEmpty()) {
                return Collections.emptyList();
            }

            List<TagDemandAnalysisResult> results = new ArrayList<>();
            for (Map<String, Object> tag : tags) {
                try {
                    String tagName = (String) tag.get("tagName");
                    List<String> similarTags = (List<String>) tag.get("similarTags");

                    if (tagName != null && !tagName.trim().isEmpty()) {
                        TagDemandAnalysisResult result = new TagDemandAnalysisResult();
                        result.setTagName(tagName.trim());
                        result.setSimilarTags(similarTags != null ? similarTags : Collections.emptyList());
                        results.add(result);
                    }
                } catch (Exception e) {
                }
            }

            return results;

        } catch (Exception e) {
            return Collections.emptyList();
        }
    }

    /**
     * 需求分析的降级方案
     */
    private List<TagDemandAnalysisResult> getFallbackDemandAnalysisResults(String demandText) {

        List<TagDemandAnalysisResult> fallbackResults = new ArrayList<>();

        // 常见的技术标签关键词
        String[] commonTechTags = {"Java", "Python", "JavaScript", "数据库", "算法", "机器学习",
                "前端", "后端", "移动开发", "云计算", "大数据", "人工智能"};

        String lowerText = demandText.toLowerCase();

        for (String tag : commonTechTags) {
            if (lowerText.contains(tag.toLowerCase())) {
                TagDemandAnalysisResult result = new TagDemandAnalysisResult();
                result.setTagName(tag);
                result.setSimilarTags(Collections.emptyList());
                fallbackResults.add(result);

                // 最多返回4个标签
                if (fallbackResults.size() >= 4) {
                    break;
                }
            }
        }

        // 如果没有任何匹配，返回一个默认标签
        if (fallbackResults.isEmpty()) {
            TagDemandAnalysisResult result = new TagDemandAnalysisResult();
            result.setTagName("技术开发");
            result.setSimilarTags(Collections.emptyList());
            fallbackResults.add(result);
        }

        return fallbackResults;
    }


    /**
     * 批量计算标签与多个任务的关联度
     * @param tagName 标签名称
     * @param assignmentDescriptions 任务ID与描述的映射
     * @return 任务ID与关联度的映射（只返回关联度>0.1的）
     */
    public Map<String, Double> batchCalculateTagRelevance(String tagName,
                                                          Map<String, String> assignmentDescriptions) {

        String prompt = buildBatchRelevancePrompt(tagName, assignmentDescriptions);
        Map<String, Object> request = buildAIModelRequest(prompt);

        try {
            Map<String, Object> response = callAIModelAPI(request);
            return parseBatchRelevanceResponse(response, assignmentDescriptions.keySet());
        } catch (Exception e) {
            return Collections.emptyMap();
        }
    }

    /**
     * 构建批量关联度分析提示词
     */
    private String buildBatchRelevancePrompt(String tagName, Map<String, String> assignmentDescriptions) {
        StringBuilder prompt = new StringBuilder();
        prompt.append("请分析技术标签 \"").append(tagName).append("\" 与以下多个任务描述的关联度。\n\n");
        prompt.append("请为每个任务给出0-1的关联度分数（1表示强相关），只返回关联度>0.1的任务。\n\n");
        prompt.append("重要：请只返回纯JSON格式，不要包含任何解释、注释、Markdown标记或其他文本。\n\n");

        prompt.append("任务列表：\n");
        for (Map.Entry<String, String> entry : assignmentDescriptions.entrySet()) {
            prompt.append("任务ID: ").append(entry.getKey()).append("\n");
            prompt.append("任务描述: ").append(entry.getValue()).append("\n");
            prompt.append("---\n");
        }

        prompt.append("\n请严格按照以下JSON格式返回，不要有任何其他内容：{\"relevant_assignments\": {\"任务ID1\": 0.8, \"任务ID2\": 0.6, ...}}");

        return prompt.toString();
    }

    /**
     * 解析批量关联度响应
     */
    @SuppressWarnings("unchecked")
    private Map<String, Double> parseBatchRelevanceResponse(Map<String, Object> response, Set<String> allAssignmentIds) {
        try {
            Map<String, Object> output = (Map<String, Object>) response.get("output");
            String content = (String) output.get("text");

            // 使用相同的清理方法处理JSON内容
            String cleanedContent = cleanJsonContent(content);

            Map<String, Object> result = objectMapper.readValue(cleanedContent, Map.class);
            Map<String, Object> relevantAssignments = (Map<String, Object>) result.get("relevant_assignments");

            Map<String, Double> relevanceMap = new HashMap<>();
            for (Map.Entry<String, Object> entry : relevantAssignments.entrySet()) {
                String assignmentId = entry.getKey();
                // 验证任务ID是否存在
                if (allAssignmentIds.contains(assignmentId)) {
                    Double relevance = ((Number) entry.getValue()).doubleValue();
                    if (relevance > 0.1) {
                        relevanceMap.put(assignmentId, relevance);
                    }
                }
            }

            return relevanceMap;

        } catch (Exception e) {
            return Collections.emptyMap();
        }
    }

    /**
     * 清理JSON内容中的Markdown代码块标记和额外文本
     */
    private String cleanJsonContent(String content) {
        if (content == null) {
            return null;
        }

        // 移除 ```json 和 ``` 标记
        String cleaned = content.replaceAll("```json", "").replaceAll("```", "").trim();

        // 查找第一个完整的JSON对象（从 { 到 }）
        int startIndex = cleaned.indexOf('{');
        int endIndex = -1;

        if (startIndex >= 0) {
            int braceCount = 0;
            boolean inString = false;
            char prevChar = 0;

            for (int i = startIndex; i < cleaned.length(); i++) {
                char c = cleaned.charAt(i);

                // 处理转义字符
                if (prevChar == '\\') {
                    prevChar = c;
                    continue;
                }

                // 处理字符串内的内容
                if (c == '"' && prevChar != '\\') {
                    inString = !inString;
                }

                // 统计大括号，但不统计字符串内的
                if (!inString) {
                    if (c == '{') {
                        braceCount++;
                    } else if (c == '}') {
                        braceCount--;
                        if (braceCount == 0) {
                            endIndex = i;
                            break;
                        }
                    }
                }

                prevChar = c;
            }
        }

        if (startIndex >= 0 && endIndex > startIndex) {
            return cleaned.substring(startIndex, endIndex + 1);
        }

        // 如果还是无法提取，尝试提取第一个 [ 到最后一个 ] 之间的内容（用于数组）
        startIndex = cleaned.indexOf('[');
        endIndex = cleaned.lastIndexOf(']');

        if (startIndex >= 0 && endIndex > startIndex) {
            return cleaned.substring(startIndex, endIndex + 1);
        }

        // 如果还是无法提取，返回原始清理后的内容
        return cleaned;
    }
}